import pymysql
import pandas as pd
import os
import json
import pandas
import traceback
import warnings
warnings.filterwarnings("ignore")
from imp import reload
import sys
import random
import time
import datetime
import numpy as np
import itertools
from loguru import logger
import send_msg_XK
import qstock as qs
MYSQL_DB = 'yxk'
MYSQL_USER = 'yxk'
MYSQL_PASS = '..mysql_Yxk'
MYSQL_HOST_M = '58.34.1.199'
MYSQL_HOST_S = '58.34.1.199'
MYSQL_PORT = 3306

from THS.THSTrader import THSTrader
trader = THSTrader(r"C:\同花顺软件\同花顺\xiadan.exe") 


def get_qsdata():
    qsdatafilepath='./qsdata.hdf'
    if os.path.exists(qsdatafilepath):
        ctime=os.path.getmtime(qsdatafilepath)
        mtime_string = datetime.datetime.fromtimestamp(int(ctime))
        diff_second=(datetime.datetime.now()-mtime_string).seconds
        if diff_second>120:
            qsdata=qs.realtime_data()
            qsdata.set_index('代码',inplace=True)
            qsdata.to_hdf(qsdatafilepath,'df')
        else:
            qsdata=pd.read_hdf(qsdatafilepath)
            print('read  history qsdata')
        return qsdata
    else:
        qsdata=qs.realtime_data()
        qsdata.set_index('代码',inplace=True)
        qsdata.to_hdf(qsdatafilepath,'df')
        return qsdata

def put_order(order_dict) :
    if order_dict['trade_qty']==0:
        return
    
    try:
        st = time.time()
        conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
        cursor = conn.cursor() 
        account=order_dict['account']
        stock_id=order_dict['stock_id']
        stock_name=order_dict['stock_name']
        trade_qty=order_dict['trade_qty']
        trade_price=order_dict['trade_price']
        trade_flag=order_dict['trade_flag']
        reason=order_dict['reason']
        trade_msg=order_dict['trade_msg']
        signal_time=order_dict['signal_time']
        signal_price=order_dict['signal_price']
        strategy_index=order_dict['strategy_index']
        condition_name=order_dict['condition_name']
        buy_mul=order_dict['buy_mul']
     
        fee=0     
        if trade_flag=='sell':
            fee=np.abs(trade_price*trade_qty*0.001)
        else:  
            fee=np.abs(trade_price*trade_qty*0.00012)
        if stock_id.startswith('600')  or stock_id.startswith('688'):
            fee=fee+np.abs(trade_price*trade_qty*0.0001)
        if fee <0.1:
            fee=0.1
        nowdatetime=int(time.strftime('%H%M'))
        if (nowdatetime<=930 ) or (nowdatetime>=1459):
            print('非交易时间')
            return
 

        finish_status='finish'
        trade_id=0
        if 'A' in account:
            try:
                if trade_flag=='sell':
                    finish_status='put'
                    returnstatus=trader.sell(stock_no=str(stock_id), amount=np.abs(trade_qty), price=trade_price) 
                    trade_id=returnstatus['entrust_no']
                elif trade_flag=='buy':
                    finish_status='put'
                    returnstatus=trader.buy(stock_no=str(stock_id), amount=np.abs(trade_qty), price=(trade_price+0.01)) 
                    trade_id=returnstatus['entrust_no']
            except Exception as e:
                traceback.print_exc()
                msg= f"put_order error e {e}"
                logger.error(msg)
                send_msg_XK.send_msg(msg,userlist="YouXiongKai")
                logger.info(f'{account} put_order_error')
                finish_status='error'
                
        upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
        `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
        `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`)\
        VALUES ('{stock_id}','{stock_name}','{account}', '{trade_flag}', CURRENT_TIMESTAMP, '{trade_price}', '{finish_status}', \
        '{trade_qty}','{reason}','{trade_msg}','{signal_time}','{signal_price}','{strategy_index}','{condition_name}',\
        '{buy_mul}','{fee}','{trade_id}','{trade_price}')"
        print(upsql1)
        cursor.execute(upsql1)
        conn.commit()
        
    except Exception as e:
        traceback.print_exc()
    
    finally:
        nowdatetime=int(time.strftime('%H%M'))
        if (nowdatetime<=930 ) or (nowdatetime>=1459):
            print('非交易时间')
            return
        et = time.time()
        msg=f"Finished put_order:{stock_id},{trade_qty},{trade_price},{trade_flag},{reason},{trade_msg},{signal_time},{signal_price}, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()


def check_pos(account) :
    if 'A' not in account:
        print('not trade account')
        return
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:      
        nowdatetime=int(time.strftime('%H%M'))
        pos_df= pd.read_sql(f"select * from `yxk_realtrade_pos` where  account='{account}' and pos>0 ;", con=conn)
        pos_df.set_index('stock_id',inplace=True)
        
        cal_pos_stock_list=list(set(pos_df.index))

        
        upsql0= f"delete from  yxk_realtrade_pos_qry where account='{account}'"
        cursor.execute(upsql0)
        conn.commit()
        
        pos_df.index=pos_df.index.astype('int')
        position=trader.get_position()
        print(list(pos_df.index.astype('int')))
        if '证券名称' not in position[0].keys():
            logger.info('got error check_pos')
            return
        for i in range(len(position)):
            
            
            stock_name=position[i]['证券名称']
            stock_id=position[i]['证券代码']
            stock_id_str=str(stock_id).zfill(6)
            stock_pos=int(position[i]['股票余额'])
            now_price=position[i]['市价']
            now_asset=position[i]['市值']
            earn_money=position[i]['盈亏']
            avg_price=position[i]['成本价']
            frozen_pos=position[i]['冻结数量']
            avg_increace=position[i]['盈亏比例(%)']
            
            cal_pos_stock_list.remove(stock_id_str)
            
#             if int(stock_id) not in  list(pos_df.index) :
#                 print(stock_id,'not in pos_df')
#                 if  nowdatetime>1500 and stock_pos>0:
#                     trade_msg=f'{round(now_price*1.01,2)}|{round(now_price*0.99,2)}|0|1.03'
#                     upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
#                     `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
#                     `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`)\
#                     VALUES ('{stock_id_str}','{stock_name}','{account}', 'buy', CURRENT_TIMESTAMP, '{avg_price}', 'finish', \
#                     '{stock_pos}','adjust','{trade_msg}','CURRENT_TIMESTAMP','{avg_price}','0','adjust',\
#                     '1','0','0','{avg_price}')"
#                     print(upsql1)
#                     cursor.execute(upsql1)
#                     conn.commit()
#                 continue
                
            
            cal_pos=pos_df.loc[int(stock_id),'pos']
            upsql1=f"INSERT INTO `yxk_realtrade_pos_qry` (`account`, `updatetime`, `stock_name`, \
            `stock_id`, `pos`, `now_price`, `now_asset`, `earn_money`, `avg_price`, `frozen_pos`,  `avg_increace`,`cal_pos`) VALUES \
            ('{account}', CURRENT_TIMESTAMP,'{stock_name}', '{stock_id_str}', '{stock_pos}','{now_price}', '{now_asset}'\
            , '{earn_money}', '{avg_price}','{frozen_pos}','{avg_increace}','{cal_pos}')"
            cursor.execute(upsql1)
            conn.commit()
            if stock_pos!=pos_df.loc[int(stock_id),'pos']:    
                msg=f"{stock_id}-{stock_name}当前仓位:{stock_pos} 计算仓位:{cal_pos} 不一致 修改交易记录"
                logger.error(msg)
                send_msg_XK.send_msg(msg,userlist="YouXiongKai")
                if  (nowdatetime>1500 or  nowdatetime<930  ) and int(stock_pos)>0:
                    deletesql=f"update`yxk_realtrade_detail` set trade_status='error_finish' where account='{account}' and stock_id='{stock_id_str}'"
                    print(deletesql)
                    cursor.execute(deletesql)
                    conn.commit()
                    
                    trade_msg=f'{round(now_price*1.01,2)}|{round(now_price*0.99,2)}|0|1.03'
                    upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
                    `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
                    `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`)\
                    VALUES ('{stock_id_str}','{stock_name}','{account}', 'buy', CURRENT_TIMESTAMP, '{avg_price}', 'finish', \
                    '{stock_pos}','adjust','{trade_msg}','CURRENT_TIMESTAMP','{avg_price}','0','adjust',\
                    '1','0','0','{avg_price}')"
                    print(upsql1)
                    cursor.execute(upsql1)
                    conn.commit()
#                 continue
                 
        for stock_id in cal_pos_stock_list:
            stock_name=pos_df.loc[stock_id,'stock_name']
            cal_pos=pos_df.loc[stock_id,'pos']
            msg=f"{stock_id}-{stock_name}当前仓位:0 计算仓位:{cal_pos} 不一致 删除历史纪录"
            logger.error(msg)
            send_msg_XK.send_msg(msg,userlist="YouXiongKai")
            if  (nowdatetime>1500 or   nowdatetime<930 ) and int(cal_pos)>0:
                deletesql=f"update`yxk_realtrade_detail` set trade_status='error_finish' where account='{account}' and stock_id='{stock_id}'"
                print(deletesql)
                cursor.execute(deletesql)
                conn.commit()
                   
#                 continue          
                
                
    except Exception as e:
        traceback.print_exc()
    
    finally:
        et = time.time()
        msg=f"Finished check_pos:, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()
      
def check_order(account):
    if 'A' not in account:
        print('not trade account')
        return
    
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:       

        sql12=f"select * from yxk_realtrade_detail where account='{account}' and trade_time> date_sub(curdate(), interval 10 day)   "
        totalorder= pd.read_sql(sql12, con=conn)
        totalorder.set_index('trade_id',inplace=True)
        totalorder.index=totalorder.index.astype(object)
        sql1=f"select * from yxk_realtrade_detail where account='{account}' and trade_status in ('put','cancel_finish','error')\
        and trade_time< date_sub(now(), interval 5 MINUTE) and trade_time>=curdate() "
        unfinishorder= pd.read_sql(sql1, con=conn)
        unfinishorder.set_index('trade_id',inplace=True)
        unfinishorder.index=unfinishorder.index.astype(object)
        if len(unfinishorder)==0:
            logger.info('got none unfinishorder')
            return
        
        unfinish_list=[]
#         print(unfinishorder)
        orderlist=trader.get_today_entrusts()
        print(orderlist)
        if len(orderlist)==0:
            logger.info('got none orderlist')
            return
        if '合同编号' not in orderlist[0].keys():
            logger.info('got error orderlist')
            return
            
         
        for i in range(len(orderlist)):
            status='unfinish'
            trade_price=orderlist[i]['成交均价']
            trade_id=str(orderlist[i]['合同编号'])
            trade_type= 'buy' if orderlist[i]['操作']=='买入' else 'sell'
            stock_id_str=str(orderlist[i]['证券代码']).zfill(6)
            trade_qty=orderlist[i]['成交数量']
            stock_name=orderlist[i]['证券名称']
            finish_flag=orderlist[i]['备注']
            making_price=orderlist[i]['成交均价']
            
            if str(trade_id) not in totalorder.index and finish_flag.startswith('已'):
                msg=f"{stock_id_str} 合同编号 {trade_id}不在trade_id"
                logger.info(msg)
                
                trade_msg=f'{round(trade_price*1.01,2)}|{round(trade_price*0.99,2)}|0|1.03'
                upsql1=f"INSERT INTO `yxk_realtrade_detail` (`stock_id`,`stock_name`,`account`, `trade_type`, `trade_time`,\
                `trade_price`, `trade_status`, `trade_qty`,`trade_reason`,`trade_msg`,`signal_time`,`signal_price`,`strategy_index`,\
                `condition_name`,`buy_mul`,`fee`,`trade_id`,`making_price`)\
                VALUES ('{stock_id_str}','{stock_name}','{account}', '{trade_type}', CURRENT_TIMESTAMP, '{trade_price}', 'finish', \
                '{trade_qty}','adjust','{trade_msg}','CURRENT_TIMESTAMP','{trade_price}','0','adjust',\
                '1','0','{trade_id}','{making_price}')"
                print(upsql1)
                cursor.execute(upsql1)
                conn.commit()
                continue
                
            if str(trade_id) not in unfinishorder.index : 
                continue
                
            total_trade_qty=int(unfinishorder.loc[trade_id,'trade_qty'])
            if trade_qty>=np.abs(total_trade_qty) :
                msg=f"{orderlist[i]['合同编号']},{orderlist[i]['成交数量']},{orderlist[i]['成交均价']},{orderlist[i]['证券代码']} 已经完成"
                logger.info(msg)
                sql1=f"update yxk_realtrade_detail set trade_price='{trade_price}' , trade_status ='finish'  \
                where trade_id='{trade_id}' "
                cursor.execute(sql1)
                conn.commit()
            elif unfinishorder.loc[trade_id,'trade_status']=='cancel_finish':    
                msg=f"{orderlist[i]['合同编号']},{orderlist[i]['成交数量']},{orderlist[i]['成交均价']},{orderlist[i]['证券代码']} 已经撤单完成 确认成交数量"
                logger.info(msg)
                total_trade_qty=np.abs(total_trade_qty)/total_trade_qty* trade_qty
                if trade_qty>0 :
                    sql1=f"update yxk_realtrade_detail set trade_price='{trade_price}', trade_qty ='{total_trade_qty}' , trade_status ='finish'  \
                    where trade_id='{trade_id}' "
                    cursor.execute(sql1)
                    conn.commit()
                else:
                    sql1=f"update yxk_realtrade_detail set  trade_qty ='0' , trade_status ='finish'  \
                    where trade_id='{trade_id}' "
                    cursor.execute(sql1)
                    conn.commit()
            else:
                msg=f"{orderlist[i]['合同编号']},{orderlist[i]['成交数量']},{orderlist[i]['成交均价']},{orderlist[i]['证券代码']} 未完成待撤单"
                logger.info(msg)
                unfinish_list.append(trade_id)
            
            
            
        time.sleep(1)
        # real_trade_tool.query_order(unfinishorder)

        for trade_id in unfinish_list:    
            sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
            ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
            cursor.execute(sql)
            conn.commit()
            try:
                
                returnstatus=trader.cancel_entrust(entrust_no=str(trade_id))
                msg=f'cancel order {trade_id} '
            
                if returnstatus['success']:
                    trade_status='cancel_finish'
                else:
                    trade_status='error'
                    msg=f"cancel_fail {trade_id}"
                    send_msg_XK.send_msg(msg,userlist="YouXiongKai")
            except Exception as e:
                traceback.print_exc()
                msg= f"check_order error e {e}"
                logger.error(msg)
                send_msg_XK.send_msg(msg,userlist="YouXiongKai")        
                trade_status='error'
            upsql1=f"update  `yxk_realtrade_detail` set trade_status='{trade_status}' where trade_id='{trade_id}'"
            print(upsql1)
            cursor.execute(upsql1)
            conn.commit()
        
    except Exception as e:
        traceback.print_exc()
        print(e)
    finally:
        et = time.time()
        msg=f"Finished check_order:{account}, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()
    
def cal_pnl(account,cash) :
    global trader
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:       
        qsdata=get_qsdata()
        sql=f"select * from yxk_realtrade_detail where trade_time> date_sub(curdate(), interval 1000 day) and trade_status  in ('finish')  and  account='{account}' order by trade_time desc"
        tradedetail= pd.read_sql(sql, con=conn)
        tradedetail['stock_id']=tradedetail['stock_id'].map(lambda x:str(x).zfill(6))
        tradedetail['money_cost']=tradedetail['trade_qty']*tradedetail['trade_price']
        tradedetail['buy_money']=tradedetail['money_cost'].map(lambda x:x if x>0 else 0)
        tradesum=tradedetail.groupby("stock_id").sum()
        tradesum=tradesum[tradesum['trade_qty']>=0]
        real_net=tradesum[tradesum['trade_qty']==0]['money_cost'].sum()-tradesum[tradesum['trade_qty']==0]['fee'].sum()
        tradesum1=tradedetail[tradedetail['trade_time']> (datetime.datetime.now() - datetime.timedelta(days = 21))].groupby("stock_id").sum()
        real_df=tradesum1[tradesum1['trade_qty']==0] 
#         real_df['rate']=round(-100*real_df['money_cost']/real_df['buy_money'],2)
        loserate=(real_df['money_cost']>=100).sum()/len(real_df)
        winrate=(real_df['money_cost']<=-100).sum()/len(real_df)

        
        stocklist_str=','.join(tradesum[tradesum['trade_qty']!=0].index)

        
        
        upsql0= f"delete from  yxk_realtrade_pos where account='{account}'"
        print(upsql0)
        cursor.execute(upsql0)
        conn.commit()
        now_market_value=0
        unreal_net=0
        for stock_id in  tradesum.index:
            if stock_id=='':
                continue
            now_price=qsdata.loc[stock_id,'最新']
            if np.isnan(now_price):
                now_price=tradedetail[tradedetail['stock_id']==stock_id].iloc[0]['trade_price']
            stock_name=qsdata.loc[stock_id,'名称']
            now_asset=now_price*tradesum.loc[stock_id,'trade_qty']
            now_market_value+=now_asset
            
#             avg_increace=now_price/avg_price
            condition_name=tradedetail[tradedetail['stock_id']==stock_id]['condition_name'].values[0]
            strategy_index=tradedetail[tradedetail['stock_id']==stock_id]['strategy_index'].values[0]
            trade_time=tradedetail[tradedetail['stock_id']==stock_id]['trade_time'].max().strftime('%Y-%m-%d %H:%M:%S') 
            
#             now_asset=0 if np.isnan(now_asset) else now_asset
            unreal_money=now_asset-tradesum.loc[stock_id,'money_cost'] if tradesum.loc[stock_id,'trade_qty']>0  else 0
            earn_money=now_asset-tradesum.loc[stock_id,'money_cost'] if tradesum.loc[stock_id,'trade_qty']>0  else -1*tradesum.loc[stock_id,'money_cost'] 
            avg_increace=round(100*earn_money/tradesum.loc[stock_id,'buy_money'] ,2)
            
          
            if stock_id in  tradesum1.index:
                avg_price=tradesum1.loc[stock_id,'money_cost']/tradesum1.loc[stock_id,'trade_qty'] if tradesum.loc[stock_id,'trade_qty']>0  else 0
                upsql1=f"INSERT ignore INTO `yxk_realtrade_pos` (`account`, `stock_name`, `stock_id`, `pos`,`updatetime`,`now_price`,`now_asset`,\
                `earn_money`,`avg_price`,`unreal_money`,`avg_increace`,`condition_name`,`strategy_index`)\
                VALUES ('{account}', '{stock_name}', '{stock_id}', '{tradesum.loc[stock_id,'trade_qty']}','{trade_time}', '{now_price}'\
                , '{now_asset}', '{earn_money}','{avg_price}','{unreal_money}','{avg_increace}','{condition_name}','{strategy_index}')"
                # print(upsql1)
                cursor.execute(upsql1)
                conn.commit()
            unreal_net+=unreal_money
            
            
        nowdatetime=int(time.strftime('%H%M'))
        # if nowdatetime==931:
        #     upsql=f"INSERT INTO `yxk_strategy_focus` (`date`, `stock_list`, `condition_name`,`condition_id`,`updatetime`,`num`) \
        #     VALUES ('{nowdate}', '{stocklist_str}', 'position','',CURRENT_TIMESTAMP,'{len(tradesum[tradesum['trade_qty']!=0].index)}')"
        #     print(upsql)
        #     cursor.execute(upsql)
        #     conn.commit()
        
       
        total_assert= now_market_value+cash
        if 'A' in account:
            # total_assert,now_market_value,cash= real_trade_tool.query_cash()
            cash_dict=trader.get_balance()
            total_assert=cash_dict['总资产']
            now_market_value=cash_dict['股票市值']
            cash=cash_dict['可用金额']
            print(cash_dict)                   

        msg=f'account:{account} total_assert:{total_assert}  cash:{cash}' 
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        
        sql=f"select * from yxk_realtrade_detail where trade_time>=curdate() and trade_status='finish' and  account='{account}' order by trade_time desc"
        tradedetail_today= pd.read_sql(sql, con=conn)
        tradedetail_today_cost=np.abs(tradedetail_today['trade_qty']*tradedetail_today['trade_price']).sum()
        tradedetail_today_count=len(tradedetail_today)
        
        
        upsql1=f"INSERT IGNORE INTO `yxk_realtrade_qry` (`account`, `updatetime`, `cash`, `market_value`, `total_assert`,\
        `flag`,`unreal_pnl`,`real_pnl`,`total_pnl`,`winrate`,`loserate`,`trade_cost`,`trade_count`) VALUES ('{account}',\
        CURRENT_TIMESTAMP, '{cash}', '{now_market_value}', '{total_assert}','calculate', '{unreal_net}', '{-1*real_net}', '{-1*real_net+unreal_net}',\
        '{winrate}', '{loserate}', '{tradedetail_today_cost}', '{tradedetail_today_count}')"
        print(upsql1)
        
        
       
        
        cursor.execute(upsql1)
        conn.commit()

    except Exception as e:
        traceback.print_exc()
        msg= f"cal_pnl error {e}"
        logger.error(msg)
        send_msg_XK.send_msg(msg,userlist="YouXiongKai")
    finally:
        et = time.time()
        msg=f"Finished cal_pnl:{account}, time: {round((et-st)/60,2)}min"
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()


def real_trade(account):
    st = time.time()
    conn = pymysql.connect(host=MYSQL_HOST_M, user=MYSQL_USER, passwd=MYSQL_PASS, db=MYSQL_DB, port=MYSQL_PORT, charset='utf8')
    cursor = conn.cursor()  
    try:
        nowdatetime=int(time.strftime('%H%M'))
        config_df = pd.read_sql(f"select * from `yxk_trade_config` where  account='{account}' ;", con=conn)
        if len(config_df)==0:
            msg=f'{account} config_df 未配置！！'
            buycost=0
            send_msg_XK.send_msg(msg,userlist="YouXiongKai")
            return
       
   
        buyflag=config_df['allow_buy_flag'][0]
        sellflag=config_df['allow_sell_flag'][0]
        buycost=config_df['buy_cost'][0]
        buy_mullimit=config_df['buy_mullimit'][0]
        win_halflimit=config_df['win_halflimit'][0]
        # lose_halflimit=config_df['lose_halflimit'][0]
        
        cash_limit=config_df['cash_limit'][0]
        can_not_trade_list=config_df['can_not_trade'][0].split(',')
        print(can_not_trade_list)
        winrate_limit=0.2
        strategy_df = pd.read_sql(f"select * from  yxk_strategy where status='ready' and insample_avg_win_rate>={winrate_limit}", con=conn)
        strategy_df.set_index('strategy_index',inplace=True)
        
        
        qsdata=get_qsdata()
        # print('2')
        day10last_time=(datetime.datetime.now()-datetime.timedelta(days=10)).strftime("%Y-%m-%d %H:%M:%S")
        min10last_time=(datetime.datetime.now()-datetime.timedelta(minutes=60)).strftime("%Y-%m-%d %H:%M:%S")
        begin_time=(datetime.datetime.now()).strftime("%Y-%m-%d 00:00:00")

        # begin_time=(datetime.datetime.now()-datetime.timedelta(days=10)).strftime("%Y-%m-%d 00:00:00")
        # min10last_time=day10last_time

        # print(min10last_time)

        last_timedf = pd.read_sql(f"select distinct updatetime from `yxk_realtrade_qry` where  account='{account}'   order by  updatetime desc;", con=conn)  # and market_value>0
        
        if len(last_timedf)==0:
            
            upsql1 = f"INSERT INTO `yxk_realtrade_qry` (`account`, `updatetime`, `cash`, `market_value`, `total_assert`,`real_pnl`,`unreal_pnl`,`total_pnl`\
                     ) VALUES ('{account}', CURRENT_TIMESTAMP, '0', '0', '0', '0', '0', '0')"
            cursor.execute(upsql1)
            conn.commit()
            buysignal_df=[]
            return 
        
        
        last_time=last_timedf.loc[0,'updatetime']
        feature_list = pd.read_sql(f"select * from `yxk_realtrade_qry` where  account='{account}' and updatetime='{last_time}'  ;", con=conn)
        updatetime=feature_list.loc[0,'updatetime'] 
   
        market_value=feature_list.loc[0,'market_value']
        cash=feature_list.loc[0,'cash']
        # real_pnl=feature_list.loc[0,'real_pnl']
        # unreal_pnl=feature_list.loc[0,'unreal_pnl']    
#         total_pnl=feature_list.loc[0,'total_pnl']   
#         winrate=feature_list.loc[0,'winrate']    
#         loserate=feature_list.loc[0,'loserate']  
        
        cash_old=cash
        logger.info(f'account:{account} market_value:{market_value}  cash:{cash}' )
        if 'A' in account:
            pos_df= pd.read_sql(f"select * from `yxk_realtrade_pos_qry` where  account='{account}'  ;", con=conn)
            pos_df.set_index('stock_id',inplace=True)
        else:
            pos_df= pd.read_sql(f"select * from `yxk_realtrade_pos` where  account='{account}'  ;", con=conn)
            pos_df.set_index('stock_id',inplace=True)
        
        
        buysignal_sql=f"select * from `yxk_tradesys_msg`  where buy_time>='{min10last_time}' \
        and buy_status in ('buy','buy_more')   order by buy_time;"
        buysignal_df= pd.read_sql(buysignal_sql, con=conn)
        # print(buysignal_sql)
       
        error_sql=f"select * from `yxk_realtrade_detail` where trade_status in ('error') and trade_time> date_sub(curdate(), interval 240 MINUTE)  ;"
        error_list= pd.read_sql(error_sql, con=conn)
        trade_list=[]
        not_need_trade_list=[]
        not_need_trade_list.extend(list(set(error_list['stock_id'])))
        msg='no need trade '+str(not_need_trade_list)
        logger.info(msg)
        
        # print('3')
       

        for i in buysignal_df.index:
                
                
                
            if nowdatetime<=933:
                print('933才买')
                continue
            buy_cost_this=buycost
            del_signal_flag=True
            continue_flag=False
            stock_id=buysignal_df.loc[i,'stock_id']
            buy_price=buysignal_df.loc[i,'buy_price']
            buy_time=buysignal_df.loc[i,'buy_time']
            last_price=qsdata.loc[stock_id,'最新']
            trade_msg=buysignal_df.loc[i,'msg']
            stock_name=qsdata.loc[stock_id,'名称']
            buy_status=buysignal_df.loc[i,'buy_status']
            strategy_index=buysignal_df.loc[i,'strategy_index']
            condition_name=buysignal_df.loc[i,'condition_name']
            
            if stock_id  not in not_need_trade_list:
                not_need_trade_list.append(stock_id)
            else:
                continue
            if buyflag!='good':
                logger.info(f'{stock_id}: buyflag!=good 不能买入')
                continue 
            
            if strategy_index not in strategy_df.index:
                logger.info(f'{stock_id} not in strategy_df.index')
                continue
            buy_mul=(strategy_df.loc[strategy_index,'real_trade_winrate']*0.6+strategy_df.loc[strategy_index,'outsimple_winrate']*0.6 )*2
            if strategy_df.loc[strategy_index,'real_trade_avgret']<-0.02:
                buy_mul=buy_mul*0.4
            elif strategy_df.loc[strategy_index,'real_trade_avgret']>0.05:
                buy_mul=buy_mul*1.4
            elif strategy_df.loc[strategy_index,'outsimple_avgret']<0:
                buy_mul=buy_mul*0.5   
            if buy_mul==0:
                buy_mul=1
            buy_mul=(1+buy_mullimit*(buy_mul-1))
            buy_cost_this=buycost*buy_mul
            
            
            if np.isnan(last_price):
                logger.info(f'{stock_id}:{stock_name} qstock 获取价格为空')
                continue_flag=True
     
            if last_price<buy_price:
                buy_price=last_price
            
       
            for cannot_trade in  can_not_trade_list:  
                if stock_id.startswith(cannot_trade) :
                    logger.info(f'{stock_id}:不能交易:{cannot_trade}')
                    del_signal_flag=False
                    continue_flag=True
            if '退'in stock_name or 'ST'in stock_name :
                logger.info(f'{stock_id}:{stock_name} 有 退或者ST')
                del_signal_flag=False
                continue_flag=True  
            elif stock_name=='' or 'st' in stock_name  or 'ST' in stock_name:
                logger.info(f'{stock_id} {stock_name} st can not buy')
                continue_flag=True    
            elif buy_price<9:
                logger.info(f'{stock_id} buy_price<9 价格太低不买')
                continue_flag=True
            elif (stock_id.startswith('688') or stock_id.startswith('300')) and   qsdata.loc[stock_id,'涨幅']<-19.8:
                logger.info(f'{stock_id}跌停就不要买入了')
                del_signal_flag=True
                continue_flag=True
            elif (stock_id.startswith('00') or stock_id.startswith('60')) and   qsdata.loc[stock_id,'涨幅']<-9.8:
                logger.info(f'{stock_id}跌停就不要买入了')
                del_signal_flag=True
                continue_flag=True
            elif (stock_id.startswith('688') or stock_id.startswith('300')) and   qsdata.loc[stock_id,'涨幅']>19.8:
                logger.info(f'{stock_id}涨停买不进去')
                del_signal_flag=True
                continue_flag=True
            elif (stock_id.startswith('00') or stock_id.startswith('60')) and   qsdata.loc[stock_id,'涨幅']>9.8:
                logger.info(f'{stock_id}涨停买不进去')
                del_signal_flag=True
                continue_flag=True
            
            elif last_price/buy_price>1.03:
                logger.info(f'{stock_id} 已经涨很多了不买了 buy_price:{buy_price} lastprice:{last_price}')
                # del_signal_flag=False
                continue_flag=True
            elif cash<(buy_cost_this+cash_limit):
                msg=f'钱不够{cash} 不能买{stock_id}'
                logger.info(msg)
                # del_signal_flag=False
                # send_msg_XK.send_msg(msg,userlist="YouXiongKai")
                continue_flag=True    

            
            if del_signal_flag:
                upsql2=f"update yxk_tradesys_msg set buy_flag='finish' where buy_time='{buy_time}' and stock_id='{stock_id}' and buy_status in ('buy','buy_more')"
                cursor.execute(upsql2)
                conn.commit()  
            if continue_flag:
                continue
                
                
                
            if stock_id in list(pos_df.index) and buy_status=='buy_more':
                print('买更多',stock_id)
                if stock_id in trade_list:
                    logger.info(f'已经在交易了，不能买:{stock_id}')  
                    continue
                buy_qty=round((buy_cost_this/200)/buy_price,0)*100
                
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':buy_qty,
                'trade_price':buy_price,
                'trade_flag':'buy',
                'reason':'buy_more',
                'trade_msg':trade_msg,
                'signal_time':buy_time, 
                'signal_price':buysignal_df.loc[i,'buy_price'], 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':buy_mul,
                }
                if buy_qty>0:
                    put_order(order_dict)
                market_value=market_value+last_price*buy_qty
                cash=cash-last_price*buy_qty
                
            elif stock_id not in list(pos_df.index) and buy_status=='buy':
                trade_df= pd.read_sql(f"select * from `yxk_realtrade_detail` where trade_time> date_sub(curdate(), interval 4 day)  and trade_qty!=0 \
                and stock_id='{stock_id}' and  account='{account}' ;", con=conn)
                if len(trade_df)>0 or stock_id in trade_list:
                    logger.info(f'4天内 有这个股票的交易，不能买:{stock_id}')  
                
                    continue
                trade_list.append(stock_id)
                print('第一次买',stock_id)
                buy_qty=round((buy_cost_this/100)/buy_price,0)*100
                
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':buy_qty,
                'trade_price':buy_price,
                'trade_flag':'buy',
                'reason':'buy_first',
                'trade_msg':trade_msg,
                'signal_time':buy_time, 
                'signal_price':buysignal_df.loc[i,'buy_price'], 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':buy_mul,
                }
                if buy_qty>0:
                    put_order(order_dict)
                market_value=market_value+last_price*buy_qty
                cash=cash-last_price*buy_qty
            elif stock_id in list(pos_df.index):
                logger.info(f'有这个股票的持仓，不用买:{stock_id}')  
                continue
                
                
        sellsignal_sql=f"select a.* from `yxk_realtrade_detail` a , yxk_realtrade_pos b \
        where a.stock_id=b.stock_id and b.pos>0 and a.trade_type='buy' and a.account='{account}' \
        and a.trade_time> date_sub(curdate(), interval 10 day)  and a.trade_status not in ('error','error_finish') and b.account='{account}' order by a.trade_time desc"
        sellsignal_df= pd.read_sql(sellsignal_sql, con=conn)
        sellsignal_df.drop_duplicates(subset='stock_id',keep='first',inplace=True)

        # print('4')
        for i in sellsignal_df.index:
            continue_flag=False 
            stock_id=sellsignal_df.loc[i,'stock_id']
            last_price=qsdata.loc[stock_id,'最新']
            stock_name=qsdata.loc[stock_id,'名称']
            
            if stock_id  not in not_need_trade_list:
                not_need_trade_list.append(stock_id)
            else:
                continue
            for cannot_trade in  can_not_trade_list:  
                if stock_id.startswith(cannot_trade) :
                    logger.info(f'{stock_id}:不能交易:{cannot_trade}')
                    continue_flag=True 
            
                
            sell_msg=sellsignal_df.loc[i,'trade_msg']
            buy_time=sellsignal_df.loc[i,'trade_time']
            buy_price=sellsignal_df.loc[i,'trade_price']
            strategy_index=sellsignal_df.loc[i,'strategy_index']
            condition_name=sellsignal_df.loc[i,'condition_name']
         
            high_price=qsdata.loc[stock_id,'最高']
            if sell_msg is None:
                logger.info(f'{stock_id}: sell_msg is None')
                continue_flag=True
           
        
        
                
            if len(sell_msg.split('|'))==2:     
                sell_msg=sell_msg+'|0|1.035'
            elif len(sell_msg.split('|'))==3:
                sell_msg=sell_msg+'|1.035'
            elif len(sell_msg.split('|'))<2:
                logger.info(f'{stock_id}: 没有标准数量msg')
                continue_flag=True
                
            sell_winlimit=float(sell_msg.split('|')[0])
            sell_drawbacklimit=float(sell_msg.split('|')[1])
            hold_days=int(sell_msg.split('|')[2])
            giveup_limit=float(sell_msg.split('|')[3])        
                
                
            if sellflag!='good':
                logger.info(f'{stock_id}: sellflag!=good不能卖出')
                continue_flag=True
                
            if  stock_id not in pos_df.index:
                logger.info(f'{stock_id}: stock_id not in pos_df.index')
                continue_flag=True
                
            elif np.isnan(last_price):
                logger.info(f'{stock_id}:{stock_name} qstock 获取价格为空')
                continue_flag=True  
           
            elif (stock_id.startswith('688') or stock_id.startswith('300')) and   qsdata.loc[stock_id,'涨幅']>19.8:
                logger.info(f'{stock_id} 涨停就不要卖出了')
                continue_flag=True   
            elif (stock_id.startswith('00') or stock_id.startswith('60')) and   qsdata.loc[stock_id,'涨幅']>9.8:
                logger.info(f'{stock_id} 涨停就不要卖出了')
                continue_flag=True  
              
            elif (stock_id.startswith('688') or stock_id.startswith('300')) and   qsdata.loc[stock_id,'涨幅']<-19.8:
                logger.info(f'{stock_id} 跌停卖不出去')
                continue_flag=True   
            elif (stock_id.startswith('00') or stock_id.startswith('60')) and   qsdata.loc[stock_id,'涨幅']<-9.8:
                logger.info(f'{stock_id} 跌停卖不出去')
                continue_flag=True       
            if continue_flag:
                continue   
                
                
                
            dmsg_sql=f"select * from `yxk_tradesys_msg` where  stock_id='{stock_id}' order by buy_time desc limit 1"
            dmsg_df= pd.read_sql(dmsg_sql, con=conn)
            if len(dmsg_df)>0:
                # daydiff=(datetime.datetime.now()-dmsg_df['buy_time'][0]).days
                daydiff=np.busday_count(  dmsg_df['buy_time'][0].date(),datetime.datetime.now().date() )
            else:   
                # daydiff = (datetime.datetime.now() - buy_time).days
                daydiff=np.busday_count( buy_time.date(),datetime.datetime.now().date() )
            if daydiff<1:
                msg=f"{stock_id} daydiff {daydiff} daydiff<1"
                logger.info(msg)    
                continue
            delldetail_sql=f"select * from `yxk_realtrade_detail` where trade_type='sell' and stock_id='{stock_id}' \
            and account='{account}' order by trade_time desc limit 1"
            delldetail_df= pd.read_sql(delldetail_sql, con=conn)
            if len(delldetail_df)>0:
                diff_time=(datetime.datetime.now()-delldetail_df['trade_time'][0]).seconds/60
                if diff_time<30:
                    logger.info(f'{stock_id} 上一次卖小于30分钟')   
                    continue      
                
          
        
            
                
            if last_price>=sell_winlimit and daydiff>=1:
                print('winlimit全卖',stock_id)
                sell_qty=-1*pos_df.loc[stock_id,'pos']
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':sell_qty,
                'trade_price':last_price,
                'trade_flag':'sell',
                'reason':'sell_all',
                'trade_msg':'winlimit',
                'signal_time':buy_time, 
                'signal_price':buy_price, 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':0,
                }
                if sell_qty<0:
                    put_order(order_dict)   
                market_value=market_value+last_price*sell_qty
                cash=cash-last_price*sell_qty
            elif daydiff>=(hold_days+1) and int(time.strftime('%H%M'))>1440:
                logger.info(f'{stock_id} hold_days全卖')
                sell_qty=-1*pos_df.loc[stock_id,'pos']
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':sell_qty,
                'trade_price':last_price,
                'trade_flag':'sell',
                'reason':'sell_all',
                'trade_msg':'hold_days',
                'signal_time':buy_time, 
                'signal_price':buy_price, 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':0,
                }
                if sell_qty<0:
                    put_order(order_dict) 
                market_value=market_value+last_price*sell_qty
                cash=cash-last_price*sell_qty
                
            elif daydiff>=(hold_days+1) and high_price/last_price>giveup_limit and last_price<buy_price:
                logger.info(f'{stock_id}giveup_zero全卖')
                sell_qty=-1*pos_df.loc[stock_id,'pos']
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':sell_qty,
                'trade_price':last_price,
                'trade_flag':'sell',
                'reason':'sell_all',
                'trade_msg':'giveup_zero',
                'signal_time':buy_time, 
                'signal_price':buy_price, 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':0,
                }
                if sell_qty<0:
                    put_order(order_dict) 
                market_value=market_value+last_price*sell_qty
                cash=cash-last_price*sell_qty     
            elif last_price>=(buy_price+(sell_winlimit-buy_price)/1.5) and daydiff>=1:
                logger.info(f'{stock_id}: winlimit卖一半')
                sell_qty=-1*round(pos_df.loc[stock_id,'pos']*win_halflimit/100)*100
                if stock_id.startswith('688') and np.abs(sell_qty)<200:
                    sell_qty=-1*pos_df.loc[stock_id,'pos']
                if (not stock_id.startswith('688'))and np.abs(sell_qty)<100:
                    sell_qty=-1*pos_df.loc[stock_id,'pos']
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':sell_qty,
                'trade_price':last_price,
                'trade_flag':'sell',
                'reason':'sell_half',
                'trade_msg':'winhalflimit',
                'signal_time':buy_time, 
                'signal_price':buy_price, 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':0,
                }
                if sell_qty<0:
                    put_order(order_dict)     
                market_value=market_value+last_price*sell_qty
                cash=cash-last_price*sell_qty
           
           
            elif last_price<=sell_drawbacklimit and daydiff>=1:
                logger.info(f'{stock_id}: drawbacklimit全卖')
                sell_qty=-1*round(pos_df.loc[stock_id,'pos']/100)*100
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':sell_qty,
                'trade_price':last_price,
                'trade_flag':'sell',
                'reason':'sell_all',
                'trade_msg':'drawbacklimit',
                'signal_time':buy_time, 
                'signal_price':buy_price, 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':0,
                }
                if sell_qty<0:
                    put_order(order_dict) 
                market_value=market_value+last_price*sell_qty
                cash=cash-last_price*sell_qty

            elif last_price<=(buy_price-(buy_price-sell_drawbacklimit)/1.5) and daydiff>=1:
                logger.info(f'{stock_id}: lose_halflimit卖一半')
                sell_qty=-1*round(pos_df.loc[stock_id,'pos']*win_halflimit/100)*100
                if stock_id.startswith('688') and np.abs(sell_qty)<200:
                    sell_qty=-1*pos_df.loc[stock_id,'pos']
                if (not stock_id.startswith('688'))and np.abs(sell_qty)<100:
                    sell_qty=-1*pos_df.loc[stock_id,'pos']
                order_dict={
                'account':account,
                'stock_id':stock_id,
                'stock_name':stock_name,
                'trade_qty':sell_qty,
                'trade_price':last_price,
                'trade_flag':'sell',
                'reason':'sell_half',
                'trade_msg':'lose_halflimit',
                'signal_time':buy_time, 
                'signal_price':buy_price, 
                'strategy_index':strategy_index,
                'condition_name':condition_name,
                'buy_mul':0,
                }
                if sell_qty<0:
                    put_order(order_dict)     
                market_value=market_value+last_price*sell_qty
                cash=cash-last_price*sell_qty
           
                
        total_assert= market_value+cash  
        # if cash_old!=cash :
        #     upsql1=f"REPLACE INTO `yxk_realtrade_qry` (`account`, `updatetime`, `cash`, `market_value`, `total_assert`,`flag`,\
        #     `real_pnl`,`unreal_pnl`,`total_pnl`,`winrate`,`loserate`) VALUES ('{account}',\
        #     CURRENT_TIMESTAMP, '{cash}', '{market_value}', '{total_assert}','calculate', '{real_pnl}', '{unreal_pnl}', '{total_pnl}', '{winrate}', '{loserate}')"
        #     cursor.execute(upsql1)
        #     conn.commit()       
        #     upsql1=f"update  `yxk_realtrade_qry` \
        #     set `cash`='{cash}', `market_value`='{market_value}', `total_assert`='{total_assert}',\
        #     where account='{account}' and updatetime='{updatetime}'"
        #     cursor.execute(upsql1)
        #     conn.commit()  
        time.sleep(1)
        nowdatetime=int(time.strftime('%H%M'))
        if nowdatetime%2==0:
            check_order(account)
        if total_assert <1000000 and 'A' not in account:
            cash=1000000-market_value
        cal_pnl(account,cash) 
        if nowdatetime%10==0:
            check_pos(account)
        
        # conn.close()  
    except Exception as e:
        traceback.print_exc()
        msg= f"real_trade error e {e}"
        logger.error(msg)
        send_msg_XK.send_msg(msg,userlist="YouXiongKai")
    finally:
        et = time.time()
        msg=f"Finished real_trade:{account}, buysignal_df:{len(buysignal_df)} time: {round((et-st)/60,2)}min"
        logger.info(msg)
        sql=f"INSERT INTO `yxk_trade_log` (`account`, `date`, `updatetime`, `log`) VALUES \
        ('{account}', '{str(datetime.datetime.now().date())}', CURRENT_TIMESTAMP, '{msg}')"
        cursor.execute(sql)
        conn.commit()
        conn.close()
        
        
        
def trade_account():
    LOG_FPATH = 'trade.log'
    logger.add(LOG_FPATH)
    account='A50549'
    while True:
        dayofday=datetime.datetime.now().isoweekday()
        weekday=int(dayofday)
        nowdatetime=int(time.strftime('%H%M'))
        logger.info("++"*20)
        timestr=f"week:{weekday} nowdatetime:{nowdatetime}"
        logger.info(timestr)
        if weekday>5:
            print('周末不交易')
            break
        if nowdatetime>=1505:
            cal_pnl(account,0) 
            check_order(account)
            check_pos(account)
            cal_pnl(account,0) 
            logger.info('超过1505 程序结束')
            break
        elif nowdatetime<932 or (nowdatetime>1129 and nowdatetime<1300) or nowdatetime>1453:
            logger.info('不是交易时间') 
            time.sleep(60)
            continue
       
        try:
            real_trade('A50549')
            time.sleep(60)
        except Exception as e:
            msg= f"real_trade error e {e}"
            logger.error(e)
            send_msg_XK.send_msg(msg,userlist="YouXiongKai")    
def trade_sim():
        
    LOG_FPATH = '/home/yxk/workspace/jupyter/log/trade.log'
    logger.add(LOG_FPATH)

    while True:
        dayofday=datetime.datetime.now().isoweekday()
        dayofday1=datetime.datetime.now().strftime('%Y-%m-%d')
        nowdate=datetime.datetime.now().strftime('%Y%m%d') 
        weekday=int(dayofday)
 
        nowdatetime=int(time.strftime('%H%M'))
        logger.info("++"*20)
        timestr=f"week:{weekday} nowdatetime:{nowdatetime}"
        logger.info(timestr)
        if nowdatetime>=1505:
            cal_pnl('123',0) 
            cal_pnl('1001',0) 
            logger.info('超过1505 程序结束')
            break
        elif nowdatetime<932 or (nowdatetime>1129 and nowdatetime<1300) or nowdatetime>1453:
            logger.info('不是交易时间') 
            time.sleep(60)
            continue
       
        try:  
            real_trade('123')
            real_trade('1001')
            time.sleep(60)
        except Exception as e:
            msg= f"real_trade error e {e}"
            logger.error(e)
            send_msg_XK.send_msg(msg,userlist="YouXiongKai")       
        
   
    ## 每1分钟查一次cash 和仓位
    ## 每分钟都去交易
    
if __name__ == '__main__': 
    


    trade_account()
   